﻿<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>学生管理</el-breadcrumb-item>
        <el-breadcrumb-item>学生列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 学生列表卡片内容区 -->
        <el-card class="box-card">
            <!-- 搜索 添加 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入学号或者姓名" v-model="queryInfo.query" clearable @clear="getStudentList"></el-input>
                </el-col>
                <el-col :span="4">
                    <el-select v-model.number="queryInfo.class_id" filterable placeholder="请选择班级">
                        <el-option label="请选择" value=""></el-option>
                        <el-option
                                v-for="item in classList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-col>
                <el-col :span="4">
                    <el-button plain type="primary" @click="getStudentList">筛选</el-button>
                </el-col>
                <el-col :span="8">
                    <el-button type="primary" @click="showAddStudentDialog" style="float: right">添加学生</el-button>
                </el-col>
            </el-row>
            <!-- 学生列表区域 -->
            <el-table :data="studentlist"
                      border stripe header-row-class-name="table_header"
                      :header-cell-style="table_header"
                      @sort-change="sortChange"
                      empty-text="暂无数据"
            >
                <el-table-column type="index" label="序号" width="50px" align="center"></el-table-column>
                <el-table-column prop="stu_id" label="学号" align="center" width="120px" sortable></el-table-column>
                <el-table-column prop="name" label="姓名" align="center" width="80px"></el-table-column>
                 <el-table-column prop="gender" label="性别" align="center" width="70px">
                     <template slot-scope="scope">
                         <el-tag v-if="scope.row.gender === 1" type="" >男</el-tag>
                         <el-tag v-else type="danger">女</el-tag>
                     </template>
                 </el-table-column>
                <el-table-column prop="birthday" label="生日" align="center" width="100px">
                    <template slot-scope="scope">{{scope.row.birthday | dateFormat }}</template>
                </el-table-column>
                <el-table-column prop="mobile" label="手机号" align="center" width="130px"></el-table-column>
                <el-table-column prop="class.name" label="班级" align="center" width="80px"></el-table-column>
                <el-table-column prop="class.major_id" label="专业" align="center" min-width="100px">
                    <template slot-scope="scope">{{ getMajorName(scope.row.class.major_id) }}</template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-tooltip
                                class="item"
                                effect="dark"
                                content="查看更多"
                                :enterable="false"
                                placement="top"
                        >
                            <el-button
                                    type="warning"
                                    icon="el-icon-setting"
                                    size="mini"
                                    circle
                                    @click="showStudentDialog(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip
                                class="item"
                                effect="dark"
                                content="编辑学生"
                                :enterable="false"
                                placement="top"
                        >
                            <el-button
                                    type="primary"
                                    icon="el-icon-edit"
                                    size="mini"
                                    circle
                                    @click="showEditStudentDialog(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip
                                class="item"
                                effect="dark"
                                content="删除学生"
                                :enterable="false"
                                placement="top"
                        >
                            <el-button
                                    type="danger"
                                    icon="el-icon-delete"
                                    size="mini"
                                    circle
                                    @click="removeStudentById(scope.row.id)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pageNum"
                    :page-sizes="[2, 5, 10, 15]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    background
                    hide-on-single-page
            ></el-pagination>
        </el-card>
        <el-dialog
            :title="Dialog_title"
            :visible.sync="StudentDialogVisible"
            width="65%"
            @close="resetForm('StudentFormRef')"
            :close-on-click-modal="false"
        >
            <el-form
                    :inline="true"
                    :model="StudentForm"
                    ref="StudentFormRef"
                    :rules="StudentFormRules"
                    label-width="100px"
            >
                <el-form-item label="姓名 " prop="name">
                    <el-input v-model="StudentForm.name"></el-input>
                </el-form-item>
                <el-form-item label="学号 " prop="stu_id">
                    <el-input type="number" v-model.number="StudentForm.stu_id"></el-input>
                </el-form-item>
                <el-form-item label="性别 " prop="gender" style="margin-right: 105px">
                    <el-radio-group v-model="StudentForm.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="身份证号 " prop="id_card">
                    <el-input v-model="StudentForm.id_card"></el-input>
                </el-form-item>
                <el-form-item label="银行卡号 " prop="bank_card_no">
                    <el-input v-model="StudentForm.bank_card_no"></el-input>
                </el-form-item>
                <el-form-item label="宿舍号 " prop="dormitory">
                    <el-input v-model="StudentForm.dormitory"></el-input>
                </el-form-item>
                <el-form-item label="政治面貌 " prop="political" align="left">
                    <el-input v-model="StudentForm.political"></el-input>
                </el-form-item>
                <el-form-item label="家庭地址 " prop="home_address">
                    <el-input v-model="StudentForm.home_address" style="width: 500px"></el-input>
                </el-form-item>
                <el-form-item label="生日 " prop="birthday">
                    <el-date-picker
                            v-model="StudentForm.birthday"
                            type="date"
                            placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="邮箱 " prop="email">
                    <el-input v-model="StudentForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机 " prop="mobile">
                    <el-input v-model="StudentForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="QQ " prop="qq">
                    <el-input v-model="StudentForm.qq"></el-input>
                </el-form-item>
                <el-form-item label="微信 " prop="we_chat">
                    <el-input v-model="StudentForm.we_chat"></el-input>
                </el-form-item>
                <el-form-item label="班级 " prop="class_id">
                    <el-select v-model="StudentForm.class_id" filterable placeholder="请选择">
                        <el-option
                                v-for="item in classList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="父亲 " prop="father_name">
                    <el-input v-model="StudentForm.father_name"></el-input>
                </el-form-item>
                <el-form-item label="父亲手机 " prop="father_mobile">
                    <el-input v-model="StudentForm.father_mobile"></el-input>
                </el-form-item>
                <el-form-item label="父亲工作单位 " prop="father_work_unit">
                    <el-input v-model="StudentForm.father_work_unit"></el-input>
                </el-form-item>
                <el-form-item label="父亲身份证号 " prop="father_id_card">
                    <el-input v-model="StudentForm.father_id_card"></el-input>
                </el-form-item>
                <el-form-item label="母亲 " prop="mather_name">
                    <el-input v-model="StudentForm.mather_name"></el-input>
                </el-form-item>
                <el-form-item label="母亲手机 " prop="mather_mobile">
                    <el-input v-model="StudentForm.mather_mobile"></el-input>
                </el-form-item>
                <el-form-item label="母亲工作单位 " prop="mather_work_unit">
                    <el-input v-model="StudentForm.mather_work_unit"></el-input>
                </el-form-item>
                <el-form-item label="母亲身份证号 " prop="mather_id_card">
                    <el-input v-model="StudentForm.mather_id_card"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="StudentDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="AddOrEditStudent">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        // 自定义邮箱规则
        var checkEmail = (rule, value, callback) => {
            const regEmail = /^\w+@\w+(\.\w+)+$/
            if (regEmail.test(value)) {
                // 合法邮箱
                return callback()
            }
            callback(new Error('请输入合法邮箱'))
        }
        // 自定义手机号规则
        var checkMobile = (rule, value, callback) => {
            const regMobile = /^1[34578]\d{9}$/
            if (regMobile.test(value)) {
                return callback()
            }
            // 返回一个错误提示
            callback(new Error('请输入合法的手机号码'))
        }
        return {
            queryInfo: {
                sort_order:'',
                sort_prop:'',
                query: '',
                class_id: null,
                // 当前页数
                pageNum: 1,
                // 每页显示多少数据
                pageSize: 10,
            },
            studentlist: [],
            total: 0,

            Dialog_title: '',
            Dialog_state: '',
            StudentDialogVisible: false,
            showStudentDialogVisible: false,

            StudentForm: {
                name: '',
                class: {},
            },
            StudentFormRules: {
                name: [
                    { required: true, message: '请输入学生姓名', trigger: 'blur' },
                ],
                stu_id: [
                    { required: true, message: '请输入学号', trigger: 'blur' },
                ],
                gender: [
                    { required: true, message: '请输入性别', trigger: 'blur' },
                ],
                id_card: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' },
                ],
                political: [
                    { required: true, message: '请输入政治面貌', trigger: 'blur' },
                ],
                birthday: [
                    { required: true, message: '请输入出生日期', trigger: 'blur' },
                ],
                mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
                class_id: [
                    { required: true, message: '请选择班级', trigger: 'blur' },
                ],
            },
            selectedKeys: [],
            // 父级分类列表
            parentMajorList: [],
            // 指定级联选择器的配置对象
            cascaderProps: {
                // 配置触发选项 hover/click
                expandTrigger: 'hover',
                value: 'id',
                label: 'name',
                children: 'children',
            },
            classList: [],
            majorMap: {},
        }
    },
    created () {
        this.getStudentList();
        this.getClassesList();
        this.getAllDepartTree();
        this.getMajorMap();
    },
    methods:{
        sortChange(row){
            this.queryInfo.sort_prop = row.prop;
            this.queryInfo.sort_order = row.order === "ascending" ? 'asc' : 'desc';
            this.getStudentList()
        },
        getMajorName(major_id){
            return this.majorMap[major_id]
        },
        resetForm (formName) {
            this.StudentForm = {class:{}};
            if (this.$refs[formName] !== undefined) {
                this.$refs[formName].resetFields();
            }
        },
        table_header(row, column, rowIndex, columnIndex){
            return 'background-color: #409EFF; color:white; font-size:14px;font-weight: bold;'
        },
        // 监听 pagesize改变的事件
        handleSizeChange (newSize) {
            this.queryInfo.pageSize = newSize;
            this.getStudentList()
        },
        // 监听 页码值 改变事件
        handleCurrentChange (newNum) {
            // console.log(newSize)
            this.queryInfo.pageNum = newNum;
            this.getStudentList()
        },
        showAddStudentDialog () {
            this.Dialog_state = "add";
            this.Dialog_title = "添加学生";
            this.StudentDialogVisible = true
        },
        // 编辑班级
        showEditStudentDialog (row) {
            this.Dialog_state = "edit";
            this.Dialog_title = "编辑学生";
            this.StudentForm = row;
            this.StudentDialogVisible = true
        },
        showStudentDialog  (row) {
            this.StudentForm = row;
            this.$router.push({name:"studentInfo", params: {id: row.stu_id, row: row}})
            // this.showStudentDialogVisible = true
        },
        // 获取学生列表
        async getStudentList () {
            const { data: res, status: status } = await this.axios.get('student/getStudentList', {
                params: this.queryInfo
            })
            if (status !== 200) {
                if (status === 202){
                    return this.$message.info("当前用户目前没有分配学生")
                }
                return this.$message.error('获取学生列表失败！')
            }
            this.studentlist = res.data.students;
            this.total = res.data.total;
        },
        // 获取班级列表
        async getClassesList() {
            const { data: res, status: status } = await this.axios.get('class/getClassList', {params: this.queryInfo})
            if (status !== 200) {
                if (status > 200 && status < 250) return;
                return this.$message.error('获取班级列表失败！')
            }
            this.classList = res.data.classes;
        },
        // 获取专业map
        async getMajorMap() {
            const { data: res, status: status } = await this.axios.get('major/getMajorMap')
            if (status !== 200) {
                return this.$message.error('获取班级列表失败！')
            }
            this.majorMap = res.data;
        },
        // 获取专业树结构列表
        async getAllDepartTree(){
            const { data: res, status: status } = await this.axios.get('department/getAllDepartmentTree')
            if (status !== 200) {
                return this.$message.error('获取部门列表树失败！')
            }
            this.parentMajorList = res.data;
        },
        // 添加学生
        AddOrEditStudent () {
            if (this.Dialog_state === "add") {
                // 提交请求前，表单预验证
                this.$refs.StudentFormRef.validate(async valid => {
                    // console.log(valid)
                    // 表单预校验失败
                    if (!valid) return
                    const {data: res, status: status} = await this.axios.post('student/addStudent', this.StudentForm);
                    if (status !== 200) {
                        this.$message.error('添加学生失败！')
                    }
                    this.$message.success('添加学生成功！');
                    this.StudentDialogVisible = false;
                    this.getStudentList()
                })
            }else {
                this.$refs.StudentFormRef.validate(async valid => {
                    if (!valid) return;
                    const { data: res, status: status } = await this.axios.put('student/updateStudent', this.StudentForm);
                    if (status !== 200) {
                        this.$message.error('更新学生信息失败！')
                    }
                    this.StudentDialogVisible = false;
                    this.$message.success('更新学生信息成功！');
                    this.getStudentList()
                })
            }
        },

        // 删除学生
        async removeStudentById (id) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除该学生, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch(err => err);
            // 点击确定 返回值为：confirm
            // 点击取消 返回值为： cancel
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res, status: status } = await this.axios.delete('student/deleteStudent', {params: {"id": id}});
            if (status !== 200) return this.$message.error('删除学生失败！');
            this.$message.success('删除学生成功！');
            this.getStudentList()
        },
    },
}
</script>
<style lang="less" scoped>

</style>